package com.example.bookkeeping1220.talk;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.bookkeeping1220.db.AccountBean;
import com.example.bookkeeping1220.db.DBManager;
import com.example.bookkeeping1220.R;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.csvreader.CsvReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.wltea.analyzer.lucene.IKAnalyzer;

@RequiresApi(api = Build.VERSION_CODES.N)
public class TalkActivity extends AppCompatActivity {
    protected MsgAdapter adapter;
    List<Msg> msgList = new ArrayList<>();
    AccountBean Bean = new AccountBean();
    HashMap<String, String> reply = new HashMap<>();

    private EditText inputText;
    private RecyclerView msgRecyclerView;

    public String displayName;
    public int displayID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_talking_main);
        inputText = findViewById(R.id.input_text);
        Drawable imagLeft = getDrawable(displayID);
        int id = DBManager.getUserHead();
        if (id == -1) id = R.drawable.head_portrait;
        Drawable imagRight = getDrawable(id);
        drawNormalize(imagLeft);
        drawNormalize(imagRight);
        adapter = new MsgAdapter(msgList, imagLeft, imagRight);
        msgRecyclerView = findViewById(R.id.msg_recycler_view);
        msgRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        msgRecyclerView.setAdapter(adapter);

        TextView nameText = findViewById(R.id.talkNameTextView);
        nameText.setText(displayName);
        Button send = findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    sendMessage();
                    replyMessage();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        ImageView backArrow = findViewById(R.id.chatBackArrow);
        backArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        reply.clear();
        try {
            readCSV("支出类型", "expend.csv");
            readCSV("收入类型", "income.csv");
//            for (HashMap.Entry<String, String> s: reply.entrySet())
//              Log.e("tag", "Key = " + s.getKey() + ", Value = " + s.getValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage() throws IOException {
        String content = inputText.getText().toString();
        if (content.isEmpty()) return;
        Log.e("content", content);
        Bean.trans(Token(content));
        msgList.add(new Msg(content, Msg.TYPE_SENT));
        adapter.notifyItemInserted(msgList.size() - 1);
        msgRecyclerView.scrollToPosition(msgList.size() - 1);
        inputText.setText("");
    }

    public void replyMessage() {
        if (Bean.getMoney() < 0 || !reply.containsKey(Bean.getTypename()))
            return;
        msgList.add(new Msg(reply.get(Bean.getTypename()), Msg.TYPE_RECEIVED));
    }

    protected void readCSV(String type, String fileName) throws IOException {
        try {
            InputStreamReader inputStream = new InputStreamReader(getAssets().open(fileName));
            CsvReader csvReader = new CsvReader(inputStream);
            csvReader.readHeaders();
            while (csvReader.readRecord())
                reply.put(csvReader.get(type), csvReader.get(displayName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<String> Token(String str) throws IOException {
        Analyzer analyzer = new IKAnalyzer();
        StringReader reader = new StringReader(str);
        TokenStream tokenStream = analyzer.tokenStream("", reader);
        CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class);
        List<String> words = new ArrayList<>();
        while (tokenStream.incrementToken())
            words.add(charTermAttribute.toString());
        reader.close();
        return words;
    }

    private void drawNormalize(Drawable draw) {
        draw.setBounds(30, 30, 30, 30);
    }
}
